package com.qinggeng.project.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.utils.SecurityUtils;
import com.qinggeng.framework.aspectj.lang.annotation.Log;
import com.qinggeng.framework.aspectj.lang.enums.BusinessType;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.framework.web.page.TableDataInfo;
import com.qinggeng.project.api.utils.ParticipleUtils;
import com.qinggeng.project.system.domain.AttrRow;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.domain.GoodsActivity;
import com.qinggeng.project.system.service.IGoodsActiviyService;
import com.qinggeng.project.system.service.IGoodsKeywordsService;
import com.qinggeng.project.system.service.IGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author 吴鹏飞
 * @date 2020/12/3
 */
@RequestMapping("/system/beatGoods")
@RestController
public class GoodsBeatController extends BaseController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsActiviyService goodsActiviyService;
    @Autowired
    private IGoodsKeywordsService keywordsService;


    /**
     * 查询商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(Goods goods) {
        goods.setDelFalg("10");
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())) {
            goods.setShopId(SecurityUtils.getShopId());
        }
        startPage();
        List<Goods> goodsSkuVoList = goodsService.selectBeatGoodsList(goods);
        return getDataTable(goodsSkuVoList);
    }


    /**
     * 新增商品信息
     */
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody Goods goods) {
        List<AttrRow> attrRows = JSONArray.parseArray(JSON.toJSONString(goods.getAttrRows()), AttrRow.class);
        try {
            //批量添加关键字
            List<String> keywordsList = ParticipleUtils.participleName(attrRows.get(0).getGoodsName());
            int count = keywordsService.insertGoodsKeywordsList(keywordsList);

            if (count<=0){
                return AjaxResult.error("插入关键字失败");
            }
            if (count!=keywordsList.size()){
                return AjaxResult.error("插入关键字个数错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            goods.setShopId(SecurityUtils.getShopId());
            goods.setAddType(CommonEnum.STATUS_20.getValue());
        }
        Long mainCategory =  goodsService.selectMaxGoodsId();

        if (mainCategory == null){

            mainCategory = 1L;
        }else {
            mainCategory +=1;
        }
        Goods goods1 = null;
        for (AttrRow attrRow : attrRows) {
            goods1 = new Goods();
            BeanUtils.copyProperties(goods,goods1);
            goods1.setAttributes(attrRow.getAttributes());
            goods1.setMainCategory(mainCategory);
            goods1.setGoodsPrice(attrRow.getGoodsPrice());
            goods1.setGroupPrice(attrRow.getGroupPrice());
            goods1.setLinePrice(attrRow.getLinePrice());
            goods1.setAttributesName("规格");
            goods1.setGoodsName(attrRow.getGoodsName());
            goods1.setGoodsImg(attrRow.getGoodsImg());
            goods1.setGoodsLongImg(attrRow.getGoodsLongImg());
            int i = goodsService.insertGoods(goods1);
            if (i<=0){
                return AjaxResult.error("新增商品失败");
            }

            //捶一捶活动
            if ("40".equals(goods1.getGoodsType())){
                GoodsActivity goodsActivity = new GoodsActivity();
                goodsActivity.setActivityName("捶一捶");
                goodsActivity.setActivityType("20");
                goodsActivity.setGoodsId(goods1.getGoodsId());
                goodsActivity.setGoodsPrice(new BigDecimal(goods1.getGoodsPrice().toString()));
                //设置捶成人数
                goodsActivity.setGroupNum(attrRow.getGroupNum());
                //插入
                int i1 = goodsActiviyService.insertGoodsActivity(goodsActivity);
                if (i1<=0){
                    return AjaxResult.error("新增捶一捶失败");
                }
            }
        }
        return AjaxResult.success("新增商品成功");
    }


    /**
     * 修改商品信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:edit')")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Goods goods) {
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            Goods goods1 = goodsService.selectGoodsById(goods.getGoodsId());
            if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                return AjaxResult.error("只能操作自己所属商品");
            }
        }
        List<AttrRow> attrRows = JSONArray.parseArray(JSON.toJSONString(goods.getAttrRows()), AttrRow.class);

        if (attrRows.size()==1){
            AttrRow attrRow=attrRows.get(0);
            goods.setAttributes(attrRow.getAttributes());
            goods.setGoodsPrice(attrRow.getGoodsPrice());
            goods.setGroupPrice(attrRow.getGroupPrice());
            goods.setLinePrice(attrRow.getLinePrice());
            goods.setGoodsName(attrRow.getGoodsName());
            goods.setGoodsImg(attrRow.getGoodsImg());
            goods.setGoodsLongImg(attrRow.getGoodsLongImg());
            //捶一捶活动商品
            if ("40".equals(goods.getGoodsType())){
                //修改捶成人数
                goodsActiviyService.updateGoodsActivityOnGroupNumByGoodsId(goods.getGoodsId(),attrRows.get(0).getGroupNum());
            }


            return AjaxResult.success("修改商品成功",goodsService.updateGoods(goods));
        }
        return AjaxResult.error("无Sku请重试");
    }
}
